package com.monkey.web.platform.infrastructure;

import com.google.common.collect.ImmutableMap;
import com.monkey.core.web.response.MonkeyResponseDto;
import com.monkey.utils.upload.FileService;
import com.monkey.web.context.Global;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * Project  : monkey
 * Author   : Wu Tian Qiang
 * Date     : 2016/9/18
 */
public abstract class AbstractUploadController {

    @Autowired
    protected FileService fileService;

    public MonkeyResponseDto uploadFile(MultipartFile file) {
        MonkeyResponseDto responseDto = new MonkeyResponseDto();
        String originalFilename = file.getOriginalFilename();
        if (!fileService.checkFileType(originalFilename, this.getAllowFileTypes())) {
            return responseDto.fail("只允许上传文件格式：" + this.allowFilesToString());
        }

        try {
            String path = fileService.temp(file, Global.getResourceTemp());
            return responseDto.success("上传成功", ImmutableMap.of("path", getResourceFullPath(path)));
        } catch (IOException e) {
            e.printStackTrace();
            return responseDto.success("上传出现异常");
        }
    }


    /**
     * 允许上传的文件列表
     *
     * @return
     */
    protected abstract List<String> getAllowFileTypes();


    protected String allowFilesToString() {
        StringBuilder sb = new StringBuilder("");
        for (String fileType : this.getAllowFileTypes()) {
            sb.append(fileType).append(",");
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }

    /**
     * 判断是否开启了在资源前面添加域名
     * 是 -> 获取资源的全地址
     * 否 -> 原样返回
     *
     * @param relatePath
     * @return
     */
    public static String getResourceFullPath(String relatePath) {
        if (Global.getResourceDomain()) {
            return Global.getResourceHost() + relatePath;
        }
        return relatePath;
    }

    /**
     * 判断是否开启在资源前面添加域名
     * 是 -> 去掉域名，返回相对地址
     * 否 -> 直接返回相对地址
     *
     * @param fullPath
     * @return
     */
    public static String getResourceRelatePath(String fullPath) {
        if (Global.getResourceDomain()) {
            return StringUtils.substringAfterLast(fullPath, Global.getResourceHost() + Global.getResourcePrePath());
        }
        return fullPath;
    }


}
